local s = require "service"

local skynet = require "skynet"
local mysql = require "skynet.db.mysql"
local socketchannel = require "skynet.socketchannel"

require "resp_account"
require "resp_query"
require "resp_save"

local db
local mysql_host = "127.0.0.1"
local mysql_port = 3306
local mysql_database = "skynetdemo"
local mysql_username = "root"
local mysql_password = "123456"


s.init = function()
    local function on_connected(db)
        skynet.error("mysql connected!")
    end

    local ok
    ok, db = pcall(mysql.connect, {
        host = mysql_host,
        port = mysql_port,
        database = mysql_database,
        user = mysql_username,
        password = mysql_password,
        max_packet_size = 1024 * 1024,
        on_connect = on_connected
    })

    if not ok or not db then
        skynet.error("connect to mysql failed")
    end

    s.db = db

    -- keep mysql alive
    skynet.fork(function()
        while true do
            if db and db ~= socketchannel.error then
                local sql = string.format("select %s", skynet.time())
                -- skynet.error("keep mysql alive, start query")
                db:query(sql)
            end

            -- sleep 60 seconds
            skynet.sleep(6000)
        end
    end)
end

s.start(...)
